package com.aihongbo.test.aidlclient

import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.util.Log
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.aihongbo.test.aidl.ILogAidlInterface
import com.aihongbo.test.aidlclient.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {

    private val TAG: String = MainActivity::class.java.simpleName
    private lateinit var binding: ActivityMainBinding
    private var logManager: ILogAidlInterface? = null

    private val mConnection = object : ServiceConnection {
        override fun onServiceConnected(
            name: ComponentName?,
            service: IBinder?
        ) {
            binding.button.text = "连接成功"
            logManager = ILogAidlInterface.Stub.asInterface(service)
        }

        override fun onServiceDisconnected(name: ComponentName?) {
            Log.d(TAG, "onServiceDisconnected")
            binding.button.text = "连接失败"
        }

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        val intentService = Intent()
        //使用组件全路径启用成功
//        intentService.setComponent(
//            ComponentName(
//                "com.aihongbo.test.aidl", "com.aihongbo.test.aidl.LogService"
//            )
//        )
        //使用action启动，必须设置package，可以成功
        intentService.setAction("com.aihongbo.logservice")
        intentService.setPackage("com.aihongbo.test.aidl")
        val res = bindService(intentService, mConnection, BIND_AUTO_CREATE)
        if (res) {
            Log.d(TAG, "=====>绑定成功")
        } else {
            Log.d(TAG, "=====>绑定失败")
        }

        binding.button.setOnClickListener {
            logManager?.sendLog("客户端test_aidl_client发送消息")
        }
    }
}